#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import glob
import sys
import getopt

import analyze_hackbench as hackbench
import analyze_netperf as netperf
import analyze_unixbench as unixbench

log_file = ""
debug_level = False
log_path = os.getcwd()
prefix = ""

ts_func = {
    "hackbench": hackbench.init,
    "netperf": netperf.init,
    "unixbench": unixbench.init
}

def analyze_logs(file):
    log_files = []
    if os.path.isfile(file):
        log_files.append(file)
    elif os.path.isdir(file):
        match_files = os.path.join(file, prefix)
        if debug_level is True:
            print("match files: {0}".format(match_files))
        for _log in glob.glob(match_files):
            log_files.append(_log)
        if len(log_files) == 0:
            print("no log file matched: {0}/{1}".format(file, prefix))
            sys.exit(2)
    else:
        print("invalid parameter: {0}".format(file))
        sys.exit(1)

    analyze_log, handler_data = ts_func[test_suite](debug_level)

    for _log in sorted(log_files):
        if debug_level is True:
            print("checking %s" % _log)
        analyze_log(_log)

    handler_data()

if __name__ == "__main__":
    try:
        options, args = getopt.getopt(sys.argv[1: ], "t:l:d:p:f:", ["ts=", "logfile=", "debug=", "logpath=", "prefix="])
    except getopt.GetoptError:
        sys.exit(1)
    for param, value in options:
        if param in ("-t", "--ts"):
            test_suite = value
        if param in ("-l", "--logfile"):
            if os.path.exists(value) is False:
                print("log_file: {0} does not exist!".format(log_file))
                sys.exit(1)
            log_file = value
            print("log_file: {0}".format(log_file))
        if param in ("-d", "--debug"):
            debug_level = True if value == "1" else False
            print("debug_level: {0}".format(debug_level))
        if param in ("-p", "--logpath"):
            log_path = value
        if param in ("-f", "--prefix"):
            prefix = value

    # only parse the log file if meet both --logfile & --prefix
    _file = log_file if len(log_file) != 0 else log_path
    analyze_logs(_file)